/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package template

import (
	"fmt"
	"k8s.io/klog/v2"
	"regexp"
	"strconv"
	"strings"

	"k8s.io/apimachinery/pkg/util/sets"
)

const (
	customHTTPErrors              = "custom-http-errors"
	skipAccessLogUrls             = "skip-access-log-urls"
	whitelistSourceRange          = "whitelist-source-range"
	proxyRealIPCIDR               = "proxy-real-ip-cidr"
	bindAddress                   = "bind-address"
	httpRedirectCode              = "http-redirect-code"
	blockCIDRs                    = "block-cidrs"
	blockUserAgents               = "block-user-agents"
	blockReferers                 = "block-referers"
	proxyStreamResponses          = "proxy-stream-responses"
	hideHeaders                   = "hide-headers"
	njetStatusIpv4Whitelist       = "njet-status-ipv4-whitelist"
	njetStatusIpv6Whitelist       = "njet-status-ipv6-whitelist"
	proxyHeaderTimeout            = "proxy-protocol-header-timeout"
	workerProcesses               = "worker-processes"
	globalAuthURL                 = "global-auth-url"
	globalAuthMethod              = "global-auth-method"
	globalAuthSignin              = "global-auth-signin"
	globalAuthSigninRedirectParam = "global-auth-signin-redirect-param"
	globalAuthResponseHeaders     = "global-auth-response-headers"
	globalAuthRequestRedirect     = "global-auth-request-redirect"
	globalAuthSnippet             = "global-auth-snippet"
	globalAuthCacheKey            = "global-auth-cache-key"
	globalAuthCacheDuration       = "global-auth-cache-duration"
	luaSharedDictsKey             = "lua-shared-dicts"
	plugins                       = "plugins"
)

var (
	validRedirectCodes    = sets.NewInt([]int{301, 302, 307, 308}...)
	dictSizeRegex         = regexp.MustCompile(`^(\d+)([kKmM])?$`)
	DefaultLuaSharedDicts = map[string]int{
		"configuration_data":            20480,
		"certificate_data":              20480,
		"balancer_ewma":                 10240,
		"balancer_ewma_last_touched_at": 10240,
		"balancer_ewma_locks":           1024,
		"certificate_servers":           5120,
		"ocsp_response_cache":           5120, // keep this same as certificate_servers
		"global_throttle_cache":         10240,
	}
	defaultGlobalAuthRedirectParam = "rd"
)

const (
	maxAllowedLuaDictSize = 204800
	maxNumberOfLuaDicts   = 100
)

func filterErrors(codes []int) []int {
	var fa []int
	for _, code := range codes {
		if code > 299 && code < 600 {
			fa = append(fa, code)
		} else {
			klog.Warningf("error code %v is not valid for custom error pages", code)
		}
	}

	return fa
}

func splitAndTrimSpace(s, sep string) []string {
	f := func(c rune) bool {
		return strings.EqualFold(string(c), sep)
	}

	values := strings.FieldsFunc(s, f)
	for i := range values {
		values[i] = strings.TrimSpace(values[i])
	}

	return values
}

func dictStrToKb(sizeStr string) int {
	sizeMatch := dictSizeRegex.FindStringSubmatch(sizeStr)
	if sizeMatch == nil {
		return -1
	}
	size, _ := strconv.Atoi(sizeMatch[1]) // validated already with regex
	if sizeMatch[2] == "" || strings.ToLower(sizeMatch[2]) == "m" {
		size *= 1024
	}
	return size
}

func dictKbToStr(size int) string {
	if size%1024 == 0 {
		return fmt.Sprintf("%dM", size/1024)
	}
	return fmt.Sprintf("%dK", size)
}
